<!-- 绩效-基础设置-目标与关键成果指标库 -->
<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew
        :title="title"
        :breadCrumb="breadCrumb"
        showBack
      ></pageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-input-search
          :style="{ width: '220px' }"
          placeholder="名称"
          search-button
          @search="getTableData"
          @press-enter="getTableData"
          v-model="params.name"
        />
      </template>
      <template #right>
        <a-button type="primary" @click="add(null)">新增指x标</a-button>
      </template>
    </ConditionBox>
    <a-table
      :columns="columns"
      ref="tableRef"
      :data="tempOkrData"
      :bordered="{ headerCell: true }"
      stripe
      :spanMethod="dataSpanMethod"
    >
      <template #status="{ record }">
        <a-space>
          <a-switch
            v-model="record.status"
            :checked-value="1"
            :unchecked-value="2"
            @change="stateChange(record)"
          ></a-switch>
        </a-space>
      </template>
      <template #optional="{ record }">
        <a-tooltip content="编辑">
          <icon-font
            type="icon-edit"
            :size="26"
            :style="{
              marginRight: '10px',
              cursor: 'pointer'
            }"
            @click="goEdit(record)"
          />
        </a-tooltip>
        <a-tooltip content="删除" position="left">
          <a-popconfirm content="是否确认删除该条数据?" @ok="del(record.id)">
            <IconFont
              type="icon-delete"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer'
              }"
            />
          </a-popconfirm>
        </a-tooltip>
      </template>
    </a-table>
  </ContentCard>
  <AddIndex
    v-model:visible="modalVisible"
    @okrIndexEmit="indexEmit"
    :data="currData"
  ></AddIndex>
</template>

<script lang="ts" setup>
import {
  GetOkrIndexList,
  PostOkrIndex,
  PutOkrIndex,
  DelOkrIndex
} from '@/apis/management/performance/baseSetting/template';
import { OkrIndex } from '@/apis/management/performance/baseSetting/template/type';
import { Message } from '@arco-design/web-vue';
import AddIndex from './IndexDrawer.vue';
const router = useRouter();
const title = '目标与关键成果指标库';
const params = reactive<{ name?: string }>({ name: void 0 });
const a = ref(1);
const breadCrumb: string[] = [
  '人事',
  '基础设置',
  '指标库',
  '目标与关键成果指标库'
];
let modalVisible = ref(false); // 判断新增弹出框是否打开
let currData = ref<OkrIndex>(); // 储存当前选中数据
let tableRef = ref();

const OkrData = reactive<{ data: OkrIndex[] }>({
  /*
    name: undefined, // 目标O
    oWeight: '', // o权重/分值
    krs: [
      {
        achievement: '',
        weight: undefined
      }
    ], // 关键成果krs
    require: '', // 完成目标及时限要求
    standard: undefined, // 评分标准
    weight: '', // 指标权重
    dataSource: '', // 评分人（userid）
    upper: '', // 评分上限
    remark: '', // 备注
    personnel: '', // 评分人是否开启0否1是
    dimensionaId: '', // 维度id
    hid: undefined // 目标id
  */
  data: []
});

// kpi的table字段
const columns: any = reactive([
  {
    title: '序号',
    dataIndex: 'index',
    width: 80
  },
  {
    title: '目标(O)',
    dataIndex: 'name',
    width: 100
  },
  {
    title: 'O权重/分值',
    dataIndex: 'weight',
    width: 200
  },
  {
    title: '关键成果(KRs)',
    dataIndex: 'achievementName',
    width: 200
  },
  {
    title: 'KR权重',
    dataIndex: 'achievementWeight',
    width: 200
  },
  {
    title: '状态',
    slotName: 'status',
    dataIndex: 'status',
    width: 90,
    align: 'center'
  },
  {
    title: '操作',
    width: 120,
    fixed: 'right',
    slotName: 'optional',
    align: 'center'
  }
]);

// 储存当前的okr值
let tempOkrData: any = computed(() => {
  let newArr: any = [];
  if (Array.isArray(OkrData.data) && OkrData.data.length > 0) {
    let i = 1;
    OkrData.data.forEach((item: OkrIndex, index: number) => {
      if (index > 0 && OkrData.data[index - 1].id === item.id) {
        item.index = OkrData.data[index - 1].index;
      } else {
        item.index = i;
        i++;
      }
      item.performanceKeyResultsIndexLibrary?.forEach((item2: any) => {
        newArr.push({
          ...item,
          achievementName: item2.result,
          achievementWeight: item2.weight
        });
      });
    });
    console.log('newArr', newArr);

    return newArr;
  } else return [];
});

// 表格合并
const dataSpanMethod = (datas: any) => {
  const { record, rowIndex, columnIndex, column } = datas;
  // 处理rowSpan
  const obj = {
    rowspan: 2,
    colspan: 1
  };
  let arr = tempOkrData.value.filter((item: any) => item.id === record.id);

  const enums = ['achievementName', 'achievementWeight'];
  if (
    !enums.includes(column.dataIndex) &&
    tempOkrData.value[rowIndex - 1]?.id !== record.id
  ) {
    obj.rowspan = arr.length;
  } else {
    obj.rowspan = 0;
  }

  return obj;
};
const stateChange = async (data: OkrIndex) => {
  await PutOkrIndex(data);
  getTableData();
};
// 新增
const add = (record: any) => {
  currData.value = {
    weightType: 1,
    status: 1,
    weight: 0,
    name: '',
    performanceKeyResultsIndexLibrary: [{ result: '', weight: 0 }]
  };
  modalVisible.value = true;
};

// 获取表格数据
const getTableData = async () => {
  try {
    const res = await GetOkrIndexList(params);
    OkrData.data = res.content || [];
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};
getTableData();
// 编辑
const goEdit = (record: any) => {
  console.log(record);
  currData.value = record;
  modalVisible.value = true;
};

// 删除某一行
const del = async (id: number) => {
  try {
    await DelOkrIndex({ ids: [id] });
    getTableData();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 弹窗自定义事件
const indexEmit = async (data: OkrIndex) => {
  console.log('record', data);
  if (data.id) {
    await PutOkrIndex(data);
  } else {
    await PostOkrIndex(data);
  }
  getTableData();
};

// 刷新表格数据
const refresh = () => {
  tableRef.value.loadData();
};
</script>

<style scoped lang="less">
:deep(.arco-table-th),
:deep(.arco-table-td) {
  height: 60px;
}
</style>
